<?php

namespace api\controllers;

use yii\web\Controller;
use Firebase\JWT\JWT;

class ApiController extends CommonController {

    public $userData;

    /**
     * 
     * @param type $action
     * @return boolean
     */
    public function beforeAction($action) {
        parent::beforeAction($action);
        $jwt = \yii::$app->request->headers->get('Authorization');
        $this->userData = JWT::decode($jwt, $this->key, array('HS256'));
        if ($this->userData->exp < time()) {
            $result = ['error' => false, 'message' => "", 'objects' => []];
            $this->setHeader(203);
            echo json_encode($result);
            exit();
        }
        //echo "<pre>";var_dump($this->userData);die;
        return true;
    }

    /**
     * 
     */
    public function uploadFile($name, $path) {
        $allow= array('image/jpeg','image/pjpeg','image/gif','image/png');
        $message = "Lỗi hệ thống";
        $file_name = "";
        if (isset($_FILES[$name])) {
            $name_file = $_FILES[$name]["name"];
            $type = $_FILES[$name]["type"];
            $size = $_FILES[$name]["size"];
            $temp = $_FILES[$name]["tmp_name"];
            $error = $_FILES[$name]["error"];
            $extension = end(explode('.', $name_file));
            $file_name = time().'.'.$extension;
            if ($error > 0)
                $message = $error;
            else {
                if (!in_array($type, $allow)) {
                    $message = "bạn chỉ được upload file jpg,png,gif";
                } else {
                    @move_uploaded_file($temp, $path.$file_name);
                    $message = "";
                }
            }
        }
        return ['message' => $message,'file' => $file_name];
    }

}
